<template>
  <div class="demo-crud">
    <Card dis-hover>
      <!-- 查询条件 -->
      <Row>
        <Form :model="params" inline :label-width="100">
          <Col :span="8">
            <FormItem label="登录名：">
              <Input type="text" v-model="params.loginName"/>
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem label="状态：">
              <Select v-model="params.state" clearable>
                <Option v-for="item in userStateEnum" :key="item.code" :value="item.code">{{item.desc}}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col v-if="moreCondition" :span="8">
            <FormItem label="用户名：">
              <Input type="text" v-model="params.userName"/>
            </FormItem>
          </Col>
          <Col v-if="moreCondition" :span="8">
            <FormItem label="手机号：">
              <Input type="text" v-model="params.phone"/>
            </FormItem>
          </Col>
          <Col v-if="moreCondition" :span="8">
            <FormItem label="创建时间起：">
              <DatePicker type="date" v-model="params.createdTimeBegin"></DatePicker>
            </FormItem>
          </Col>
          <Col v-if="moreCondition" :span="8">
            <FormItem label="创建时间止：">
              <DatePicker type="date" v-model="params.createdTimeEnd"></DatePicker>
            </FormItem>
          </Col>
        </Form>
        <div style="position:relative; float:right;bottom:0px;">
          <Button type="primary" @click="handleQuery">查询</Button>
          <Button @click="reset">重置</Button>
          <Button v-if="moreCondition==false" type="text" @click="moreCondition=true">展开
            <Icon type="ios-arrow-down"></Icon>
          </Button>
          <Button v-if="moreCondition==true" type="text" @click="moreCondition=false">收起
            <Icon type="ios-arrow-up"></Icon>
          </Button>
        </div>
      </Row>
      <!-- 增加、批量处理命令 -->
      <Row>
        <Col :span="12">
          <Button type="primary" @click="showAdd">增加</Button>
          <span style="margin-left: 8px;">
            <Dropdown placement="bottom-start" @on-click="action">
              <Button type="text">批量操作<Icon type="ios-arrow-down"></Icon></Button>
            <DropdownMenu slot="list">
              <DropdownItem name="deleteBatch">批量删除</DropdownItem>
              <DropdownItem name="exportSelectionToCsv">导出选中数据到csv</DropdownItem>
              <DropdownItem name="exportAllToCsv">导出所有数据到csv</DropdownItem>
            </DropdownMenu>
            </Dropdown>
          </span>
        </Col>
      </Row>
    </Card>
    <!-- 列表 -->
    <div class="view-table">
      <Table :data="tableData"
             :columns="tableColumns"
             size="small"
             highlight-row
             :loading="isLoading"
             @on-selection-change="select"
             @on-row-dblclick="showDetail"
             ref="table">
        <template slot-scope="{ row, index }" slot="action">
          <Button type="primary" ghost size="small" style="margin-right: 10px" @click="showUpdate(row)">编辑</Button>
          <Dropdown :transfer="true" placement="bottom-start" @on-click="action">
            <Button type="text" size="small">
              更多
              <Icon type="ios-arrow-down"></Icon>
            </Button>
            <DropdownMenu slot="list">
              <DropdownItem :name="'deleteOne:' + row._index">删除</DropdownItem>
            </DropdownMenu>
          </Dropdown>
        </template>
      </Table>
    </div>
    <!-- 分页 -->
    <div class="view-page">
      <Page :total="page.total"
            :current="page.currentPage"
            :page-size="page.pageSize"
            :page-size-opts="[10,20,50,100]"
            size="small"
            show-total
            show-elevator
            show-sizer
            @on-change="pageChange"
            @on-page-size-change="pageSizeChange"/>
    </div>
    <Add :visible.sync="addFormVisible" @on-ok="handleQuery"></Add>
    <Update :visible.sync="updateFormVisible" :init-form-data="clickRow" @on-ok="handleQuery"></Update>
    <Detail :visible.sync="detailVisible" :init-form-data="clickRow"></Detail>
  </div>
</template>

<script>
  import {getDayBefore, timeToString} from "@/util/dateUtil";
  import {getUserStateDesc, getUserStateEnum} from '@/enum/SysEnum'
  import {getUserPage} from '@/api/sys/user'
  import Add from "./add"
  import Update from "./update"
  import Detail from "./detail"

  export default {
    name: "index",
    components: {Add, Update, Detail},
    data() {
      return {
        userStateEnum: getUserStateEnum(),
        params: {
          loginName: null,
          state: null,
          userName: null,
          phone: null,
          createdTimeBegin: getDayBefore(new Date(), 7),
          createdTimeEnd: new Date()
        },
        moreCondition: false,
        tableData: [],
        tableColumns: [
          {
            type: 'selection',
            width: '60'
          },
          {
            title: 'id',
            key: 'id'
          },
          {
            title: '登录名',
            key: 'loginName'
          },
          {
            title: '状态',
            key: 'stateStr',
            align: 'center'
          },
          {
            title: '创建时间',
            key: 'createdTimeStr',
            align: 'center'
          },
          {
            title: '操作',
            slot: 'action',
            width: 200,
            align: 'center',
            fixed: 'right'
          }
        ],
        selection: [],
        clickRow: {},
        isLoading: false,
        page: {
          total: 0,
          currentPage: 1,
          pageSize: 10
        },
        addFormVisible: false,
        updateFormVisible: false,
        detailVisible: false
      }
    },
    created() {
      this.query()
    },
    methods: {
      handleQuery() {
        this.page = {
          total: 0,
          currentPage: 1,
          pageSize: 10
        }
        this.query()
      },
      query() {
        const self = this
        self.isLoading = true
        let params = {
          currentPage: self.page.currentPage,
          pageSize: self.page.pageSize,
          loginName: self.params.loginName,
          state: self.params.state
        }
        if (self.moreCondition) {
          params.userName = self.params.userName
          params.phone = self.params.phone
          params.createdTimeBegin = self.params.createdTimeBegin
          params.createdTimeEnd = self.params.createdTimeEnd
        }
        getUserPage(params)
          .then((response) => {
            let result = response.data
            self.tableData = result.data
            for (let i = 0; i < self.tableData.length; i++) {
              const element = self.tableData[i];
              if (element.state != null) {
                element.stateStr = getUserStateDesc(element.state)
              }
              if (element.createdTime != null) {
                element.createdTimeStr = timeToString(element.createdTime)
              }
            }
            self.page.total = result.total

            self.isLoading = false
          })
          .catch((err) => {
            self.isLoading = false
            self.$Message.error({
              content: err,
              duration: 10,
              closable: true
            })
          });
      },
      select(selection) {
        this.selection = selection
      },
      pageChange(currentPage) {
        this.page.currentPage = currentPage
        this.query()
      },
      pageSizeChange(pageSize) {
        this.page.pageSize = pageSize
        this.query()
      },
      reset() {
        this.params = {
          loginName: null,
          state: null,
          createdTimeBegin: this.moment().subtract(7, 'days').toDate(),
          createdTimeEnd: new Date()
        }

      },
      showAdd() {
        this.addFormVisible = true
      },
      showUpdate(row) {
        this.clickRow = row
        this.updateFormVisible = true
      },
      showDetail(row) {
        this.clickRow = row
        this.detailVisible = true
      },
      deleteOne(index) {
        let row = this.tableData[index]
        this.$Modal.confirm({
          "title": "提醒",
          "content": "是否删除用户[" + row.loginName + "]?",
          "onOk": () => {
            console.log('删除' + row.loginName)
          },
          "onCancel": () => {
            console.log('不删除' + row.loginName)
          }
        })
      },
      action(cmd) {
        if (cmd === 'exportSelectionToCsv') {
          if (this.selection == null || this.selection.length == 0) {
            return
          }
          this.$refs.table.exportCsv({
            filename: '用户信息',
            columns: this.tableColumns.filter((item) => {
              return item.key != undefined
            }),
            data: this.selection
          });
        } else if (cmd === 'exportAllToCsv') {
          console.log('导出所有数据');
        } else if (cmd === 'deleteBatch') {
          if (this.selection == null || this.selection.length == 0) {
            return
          }
          let ids = [];
          let names = [];
          for (let i = 0; i < this.selection.length; i++) {
            ids.push(this.selection[i].id)
            names.push(this.selection[i].loginName)
          }
          this.$Modal.confirm({
            "title": "提醒",
            "content": "是否删除用户" + JSON.stringify(names) + "?",
            "onOk": () => {
              console.log('删除用户：' + JSON.stringify(names))
            },
            "onCancel": () => {
              console.log('不删除')
            }
          });
        } else if (cmd.indexOf('deleteOne') > -1) {
          let index = cmd.split(':')[1];
          this.deleteOne(index);
        }
      }
    }
  }
</script>

<style scoped>
  .demo-crud {

  }

</style>
